package com.amkai.aes.webservice.binary.objecthandler.billing;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.billing.PatientStatementHistoryJob;
import com.amkai.aes.generatedbeans.bill.BillStatusKind;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.diee.utils.Utils;

public class PatientStatementHistoryHandler implements JobObjectHandler<PatientStatementHistoryJob, Serializable, Serializable> {

	protected static final String BEGIN_DATE = "beginDate";
	protected static final String END_DATE = "endDate";
	protected static final String ACCOUNT = "account";

	private static final Log logger = LogFactory.getLog(PatientStatementHistoryHandler.class);

	@Override
	public Boolean process(final PatientStatementHistoryJob job, Serializable object) throws Exception {
		try {
			String hqlStr = "select id from PatientStatement where (created between :" + BEGIN_DATE + " and :" + END_DATE + ") and account.accountNumber = :" + ACCOUNT + " AND billStatusWrapper.id IN (:billed, :mark_as_billed)";
			
			SessionManager sm = SiteManager.Start();
			Query q = sm.execute(hqlStr);
			// AES-15371
			q.setTimestamp(BEGIN_DATE, Utils.truncateTime(job.beginDate, job.getTimeZone()));
			q.setTimestamp(END_DATE, Utils.getEndOfDay(job.endDate, job.getTimeZone()));
			q.setString(ACCOUNT, job.accountNumber);
			q.setInteger("billed", BillStatusKind.BILLED.ordinal());
			q.setInteger("mark_as_billed", BillStatusKind.MARK_AS_BILLED.ordinal());

			return !q.list().isEmpty();
			
		} catch (Exception e) {
			logger.error("PatientStatementHistoryHandler: ", e);
			throw e;
		}
	}

}
